<?php


namespace app\admin\controller;


use app\admin\model\MoneyTakeOut;
use app\admin\model\MoneyTakeOutProcess;
use app\common\model\AdPlayHistory;
use app\common\model\Ecpm;
use app\common\model\Money;
use app\common\model\UserIncome;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;
use think\facade\Config;
use think\facade\Request;
use app\user\model\User as UserModel;
use app\common\model\Setting as SettingModel;

class Income extends Controller
{
    protected $middleware = [
        'app\http\middleware\checkAdminToken::class'
    ];

    //资金解冻
    public function unfreezeMoney()
    {
        //解冻日期之前的资金
        $date = Request::param('date', 0);

        //获取用户的所有冻结资金
        $list=UserIncome::where([
            ['add_time','<',$date],    //截止日期之前的资金
            ['freeze','=',1],          //冻结的资金
        ])->field(['user_id','lv_1_id','lv_2_id','sum(money) as  sum_money','sum(lv_1_income) as  sum_lv_1_income','sum(lv_2_income) as  sum_lv_2_income'])
            ->group('user_id')
            ->select();


        for ($i =0;$i<count($list);$i++){
            $user_id= $list[$i]->user_id;
            $sum_money=$list[$i]->sum_money;
            $lv_1_id= $list[$i]->lv_1_id;
            $sum_lv_1_income=$list[$i]->sum_lv_1_income;
            $lv_2_id= $list[$i]->lv_2_id;
            $sum_lv_2_income=$list[$i]->sum_lv_2_income;

            //将资金记录设置为解冻
            $res=UserIncome::where([
                ['user_id','=', $user_id],        //冻结的资金
                ['add_time','<',$date],           //截止日期之前的资金
                ['freeze','=',1],                 //冻结的资金
            ])->update([
                'freeze'=>2
            ]);


           //为流量主添加可提现金额
            $res2= Money::addCanTakeOutMoney($user_id,$sum_money);

            //为1级分销增加收益
            $res2= Money::addCanTakeOutMoney($lv_1_id,$sum_lv_1_income);

            //为2级分销增加收益
            $res2= Money::addCanTakeOutMoney($lv_2_id,$sum_lv_2_income);

        }

        $this->result('',200);
    }

    //提现申请列表
    public function takeOutList()
    {

        $page = Request::param('page', 1);
        $status = Request::param('status', 0);
        $pageSize = Request::param('pageSize', 20);           //哪一天的数据

        $key = Request::param('key', '');
        if (is_numeric($key)) {
            $where2 = 'user.id=' . $key;
        } else {
            $where2 = "user.username like  '%$key%' ";
        }

        $where=[];
        if($status){
            array_push($where,['money_take_out.status','=',$status]);
        }

        $list = Db::table('money_take_out')
            ->leftJoin('user', 'money_take_out.user_id=user.id')
            ->where($where)
            ->where($where2)
            ->field(['money_take_out.user_id',"money_take_out.id as money_take_out_id",'user.username','user.avatar','money_take_out.money as take_out_money','money_take_out.alipay_name','money_take_out.alipay_account', 'money_take_out.status','user.mobile','money_take_out.add_time'])
            ->withAttr('add_time', function($value, $data) {
                return date("Y-m-d H:i:s", $value);
            })
            ->page($page, $pageSize)->select();

        $count =  Db::table('money_take_out')
            ->leftJoin('user', 'money_take_out.user_id=user.id')
            ->where($where)
            ->where($where2)->count('user.id');

        $data = [
            'list' => $list,
            'page_num' => ceil($count / $pageSize),
            'page' => $page
        ];

        $this->result($data, 200);
    }

    //确认提现
    public function takeConfirm()
    {
        //1，同意，0，拒绝
        $status = Request::param('status',0);
        $take_id = Request::param('take_id',0);

        $money_take = MoneyTakeOut::alias('m')
            ->field('m.*,user.wx_openid')
            ->leftJoin('user', 'm.user_id=user.id')
            ->where('m.id',$take_id)
            ->where('m.status',1)
            ->find();

        if(empty($money_take)) {
            $this->result(null,400,'该订单已提现');
        }

        $take_status = $status ==1 ? 2 : -1;
        $take_desc = $status ==1 ? "提现成功" : "提现拒绝";

        //更新状态
        $money_take->status = $take_status;
        $money_take->save();
        //记录日志
        $take_log = MoneyTakeOutProcess::create([
            'money_take_out_id'  =>  $take_id,
            'status' =>  $status,
            'desc' =>  $take_desc,
            'add_time'=>time()
        ]);

        //同意操作打款,拒绝退回余额
        if($status==1){
            $setting = SettingModel::getAllSetting();
            $money = $money_take['money'];

            if(!empty($setting['payment_ratio'])){
                $payment =  round((100-$setting['payment_ratio'])/100,2);
                $money = $payment * $money_take['money'];
            }

            //打款操作
//            $res = self::payMoney($money_take['wx_openid'],$money);
//            if($res['result_code'] == "FAIL"){
//                $this->result($res,400,'失败');
//            }
            $this->result($money_take['money'],200,'操作成功');
        }else{

            //拒绝提现申请的时候，将钱退回
            $res3=Money::addCanTakeOutMoney($money_take['user_id'],$money_take['money']);
            $this->result($money_take['money'],200,'操作成功，已经退款');
        }


            $this->result('',400,'操作失败');

     }

    public function payMoney($open_id,$amount=1,$desc='推广佣金')
    {
        $config = Config::get("miniprogram.wechat_pay");
        $app = Factory::payment($config);
        //提现金额转换为分
        $amount = $amount *100;
        $res = $app->transfer->toBalance(
            [
                'partner_trade_no' => time(), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                'openid' => $open_id,
                'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                're_user_name' => '邹甜', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                'amount' => intval($amount), // 企业付款金额，单位为分
                'desc' => $desc, // 企业付款操作说明信息。必填
            ]
        );
        return $res;
    }

    //更改订单的状态
    public function changeTakeOutStatus()
    {
        $status= Request::param('status');
        $money_take_out_id= Request::param('money_take_out_id');
        $order=MoneyTakeOut::get($money_take_out_id);

        //已经处理了，不能更改
        if($order->status!=1){
            $this->result(null,400,'不能重复修改订单状态');
        }

        $order->status=$status;
        $res=$order->save();

        if($res){
            $this->result($res,200,'修改成功');
        }else{
            $this->result($res,400,'失败');
        }
    }

    //添加ecpm
    public function addEcpm()
    {

        $ecpm = Request::param('ecpm', 0);

        if ($ecpm == 0) {
            $this->result('', 400, 'ecpm错误');
        }

        //计算ecpm
        $res = Ecpm::create([
            'yesterday_ecpm' => $ecpm,
            'add_time' => time()
        ]);

//        try {
        $this->calcIncome($ecpm, 0.6);

        $this->result('', 200);
//        } catch (\Exception $e) {
//            //删除失败的ecpm
//            $res2 = Db::name('ecpm')->where([
//                ['add_time', 'BETWEEN', today()]
//            ])->delete();
//            $this->result(null, 400, $e->getMessage());
//        }

    }

    //计算每天的收益(ecpm值，流量主提成比例，例：0.6)
    private function calcIncome($ecpm, $pro)
    {
        //昨天的开始时间戳和结束时间戳
        $yesterday = yesterday();

        $yesterday_ecpm = $ecpm;

        //计算分销用户的收益(vip为1的是会员用户)
        $ad_play_history = AdPlayHistory::alias('ad')->where([
            ['ad.add_time', 'BETWEEN', $yesterday]
        ])->join('user user', 'ad.promote_user_id=user.id')
            ->field('promote_user_id,count(promote_user_id) as play_count,user.vip,user.lv_1_id,user.lv_2_id')
            ->group('promote_user_id')
            ->select();

        //计算每个用户的激励视频收益，并且插入数据库
        $user_income = [];

        foreach ($ad_play_history as $key => $value) {

            //扣除前的总收益为 ecpm/1000 * 完整播放次数   结果四舍五入，保留两位小数
            $money = round($yesterday_ecpm / 1000 * $value['play_count'], 2);

            //所有用户的激励视频收益记录
            array_push($user_income, [
                'user_id' => $value['promote_user_id'],
                'lv_1_id' => 0,
                'lv_2_id' => 0,
                'money' => round($money * $pro, 2),
                'lv_1_income' => 0,
                'lv_2_income' => 0,
                'views' => $value['play_count'],
                'ecpm' => $yesterday_ecpm,
                'add_time' => time()
            ]);

            //对流量主的金额进行更新
            Db::table('user')
                ->where('id', $value['promote_user_id'])
                ->inc('money', round($money * $pro, 2))
                ->update();
        }

        //为了防止重复计算，对昨天的进行删除操作，再插入
        $res2 = Db::name('user_income')->where([
            ['add_time', 'BETWEEN', today()]
        ])->delete();

        $this->result($user_income, 200);
//        流量主收益插入数据库
        $res = Db::name('user_income')->data($user_income)->insertAll();
    }

    //ecpm的列表
    public function ecpm()
    {
        $page = Request::param('page', 1);
        $pageSize = Request::param('pageSize', 20);           //哪一天的数据
        $list = Db::table('ecpm')->withAttr('add_time', function ($value, $data) {
            return date("Y-m-d H:i:s", $value);
        })->page($page, $pageSize)->select();

        $count = Db::table('ecpm')->count('id');

        $data = [
            'list' => $list,
            'page_num' => ceil($count / $pageSize),
            'page' => $page
        ];

        $this->result($data, 200);
    }

    public function index()
    {
        $page = Request::param('page', 1);
        $key = Request::param('key', '');
        $date = Request::param('date');           //哪一天的数据
        $pageSize = Request::param('pageSize', 20);           //哪一天的数据
        $today = today();                               //今天的开始时间和结束时间

        if (is_numeric($key)) {
            $where = 'user.id=' . $key;
        } else {
            $where = "user.username like  '%$key%' ";
        }

        //收益排行
        $ad_income_rank = UserIncome::join('user', 'user_income.user_id=user.id')
//            ->where([
////                ['user_income.add_time', 'BETWEEN', $today],
//                ['username','like',$key]
//            ])
            ->where($where)
            ->field(['user.id',  "FROM_UNIXTIME(user_income.add_time,'%Y-%m-%d %H:%i:%s') as add_time", 'user.username', 'user.avatar', 'user_income.money'])
            ->page($page, $pageSize)
            ->order('user_income.add_time', 'desc')
            ->select();

        $count = UserIncome::where([
            ['user_income.add_time', 'BETWEEN', $today]
        ])->count('user_id');

        $data = [
            'list' => $ad_income_rank,
            'page_num' => ceil($count / $pageSize),
            'page' => $page
        ];
        $this->result($data, 200);
    }

}
